package com.zhangsr.zk.client.listener;

import org.apache.log4j.Logger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: zhangsr
 */
public class ZkEventThread extends Thread {

    private static final Logger log = Logger.getLogger(ZkEventThread.class);

    private BlockingQueue<ZkEvent> events = new LinkedBlockingQueue<ZkEvent>();
    private static AtomicInteger eventId = new AtomicInteger(0);

    static abstract class ZkEvent {

        private String description;

        public ZkEvent(String description) {
            this.description = description;
        }

        public abstract void run() throws Exception;

        @Override
        public String toString() {
            return "ZkEvent[" + description + "]";
        }
    }

    @Override
    public void run() {
        log.info("Starting ZkClient event thread.");
        try {
            while (!isInterrupted()) {
                ZkEvent zkEvent = events.take();
                try {
                    zkEvent.run();
                } catch (Exception e) {

                }
            }
        } catch (Exception e) {

        }
    }

    public void send(ZkEvent event) {
        if (!isInterrupted()) {
            log.debug("New event : " + event);
            events.add(event);
        }
    }
}
